package logic

import (
	"context"
	"errors"
	"gorm.io/gorm"
	"person/models/mysql"

	"person/userrpc/internal/svc"
	"person/userrpc/userrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type PerfectUserLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewPerfectUserLogic(ctx context.Context, svcCtx *svc.ServiceContext) *PerfectUserLogic {
	return &PerfectUserLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *PerfectUserLogic) PerfectUser(in *userrpc.PerfectUserRequest) (*userrpc.PerfectUserResponse, error) {
	// todo: add your logic here and delete this line

	var finduser mysql.User
	err := finduser.FindUser(mysql.DB, in.UserId)
	if err != nil {
		return nil, errors.New("查找失败")
	}
	if finduser.ID == 0 {
		return nil, errors.New("用户不存在")
	}

	user := &mysql.User{
		Model:    gorm.Model{ID: uint(in.UserId)},
		NickName: in.NickName,
		Address:  in.Address,
	}
	err = user.UpdateUser(mysql.DB)
	if err != nil {
		return nil, errors.New("修改失败")
	}

	return &userrpc.PerfectUserResponse{
		UserId: int64(user.ID),
	}, nil
}
